from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.db import connection
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm

# 辅助函数：将查询结果转换为字典
def dictfetchall(cursor):
    """将游标返回的结果转换为字典"""
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

# Create your views here.

@login_required
def profile_view(request):
    """用户个人中心视图"""
    user_id = request.user.user_id
    context = {
        'title': '个人中心'
    }
    
    # 获取用户订单
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT order_id, order_no, total_amount, status, create_time, update_time
            FROM tb_order
            WHERE user_id = %s
            ORDER BY create_time DESC
            LIMIT 10
        """, [user_id])
        
        context['orders'] = dictfetchall(cursor)
    
    # 获取用户购物车
    with connection.cursor() as cursor:
        # 获取购物车商品
        cursor.execute("""
            SELECT cart_id, box_id, quantity, selected, 
                   create_time, update_time
            FROM tb_cart
            WHERE user_id = %s
            ORDER BY update_time DESC
            LIMIT 5
        """, [user_id])
        
        user_cart_items = dictfetchall(cursor)
        
        if user_cart_items:
            # 获取对应的盲盒信息
            box_ids = [item['box_id'] for item in user_cart_items]
            
            placeholders = ', '.join(['%s'] * len(box_ids))
            cursor.execute(f"""
                SELECT box_id, name, image_url, discount_price, original_price, stock
                FROM tb_blind_box
                WHERE box_id IN ({placeholders})
            """, box_ids)
            
            box_info = {box['box_id']: box for box in dictfetchall(cursor)}
            
            # 组合购物车项目
            cart_items = []
            
            for item in user_cart_items:
                box_id = item['box_id']
                if box_id in box_info:
                    cart_item = {
                        'cart_item_id': item['cart_id'],
                        'box_id': box_id,
                        'quantity': item['quantity'],
                        'selected': item['selected'],
                        'name': box_info[box_id]['name'],
                        'image_url': box_info[box_id]['image_url'],
                        'discount_price': box_info[box_id]['discount_price'],
                        'original_price': box_info[box_id]['original_price'],
                        'item_total': item['quantity'] * box_info[box_id]['discount_price']
                    }
                    cart_items.append(cart_item)
            
            context['cart_items'] = cart_items
    
    return render(request, 'accounts/profile.html', context)

@login_required
def update_profile(request):
    """更新用户资料"""
    if request.method == 'POST':
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        user_id = request.user.user_id
        
        try:
            with connection.cursor() as cursor:
                cursor.execute("""
                    UPDATE tb_user
                    SET email = %s, phone = %s
                    WHERE user_id = %s
                """, [email, phone, user_id])
                
                # 更新当前会话中的用户信息
                request.user.email = email
                request.user.phone = phone
                
                messages.success(request, '个人资料已更新')
        except Exception as e:
            messages.error(request, f'更新资料失败: {str(e)}')
    
    return redirect('accounts:profile')

@login_required
def change_password(request):
    """修改密码"""
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            # 重要：更新会话，防止密码更改后用户被登出
            update_session_auth_hash(request, user)
            messages.success(request, '密码已成功修改')
            return redirect('accounts:profile')
        else:
            for error in form.errors.values():
                messages.error(request, error)
    else:
        form = PasswordChangeForm(request.user)
    
    return render(request, 'accounts/change_password.html', {
        'title': '修改密码',
        'form': form
    }) 